package com.hunter.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

public class HttpClientUtils {

    //新库地址

    private final static String LOGIN_NAME = "smsMan";
    private final static String LOGIN_PASSWORD = "123456";

    private final static String LOGIN_URL = "https://xingtai.video110.cn:8000/skynet/api/login/sms";
    private final static String POLICE_URL = "https://xingtai.video110.cn:8000/skynet/api/reg/alarmCaseInfo?";
    private final static String FACE_URL = "https://xingtai.video110.cn:8000/skynet/api/reg/FaceInfo?";
    private final static String HUZHENG_URL = "https://xingtai.video110.cn:8000/skynet/api/huzheng/";

    /*private final static String LOGIN_URL = "http://192.168.0.69/skynet/api/login/sms";
    private final static String POLICE_URL = "http://192.168.0.69/skynet/api/reg/alarmCaseInfo?";
    private final static String FACE_URL = "http://192.168.0.69/skynet/api/reg/FaceInfo?";
    private final static String HUZHENG_URL = "http://192.168.0.69/skynet/api/huzheng/";*/

    private static String token = "";

    public static void get(Map<String, Object> params) throws UnsupportedEncodingException {
        String url = "";
        //根据短信内容标志位来判断该调用哪个接口 为J 则为报警接口回调 , F 则为户籍比对接口回调
        String mark = (String)params.get("mark");
        if (mark.startsWith("J")){
            url = POLICE_URL;
        }else if(mark.startsWith("F")){
            url = FACE_URL;
        }else if(mark.startsWith("HZ")){
           url = HUZHENG_URL + mark + "?";
        }
        url = makeUrl(url, params);
        String res = httpGetRequest(url);
        if(res == null){
            httpGetRequest(url);
        }
    }

    //拼接短信平台get方式调用http
    public static String makeUrl(String url,Map<String, Object> params){
        try{
            Set<String> keySet = params.keySet();
            int index = 0;
            for(String key : keySet){
                String value = "";
                if(params.get(key) instanceof JSONObject){
                    value = ((JSONObject) params.get(key)).toJSONString();
                    value = URLEncoder.encode(value, "utf-8");
                }else{
                    value = (String)params.get(key);
                    value = URLEncoder.encode(value, "utf-8");
                }
                if(index == 0){
                    url += key+"=" + value;
                }else{
                    url += "&"+key+"=" + value;
                }
                 index++;
            }
            System.out.println(url);
            return url;
        }catch (Exception e){
            e.printStackTrace();
            return "";
        }
    }

    public static String httpGetRequest(String url) {
        String result = null;
        try {
            HttpGet httpGet = new HttpGet(url);
            httpGet.setHeader("APP_TOKEN", token);
            HttpResponse response = HttpClients.createDefault().execute(httpGet);
            String responseString = EntityUtils.toString(response.getEntity());
            if(response.getStatusLine().getStatusCode() == 200) {//如果cookie超时则重新登录后请求
                JSONObject jsonObject = JSON.parseObject(responseString);
                if(!jsonObject.getBoolean("status") && jsonObject.getInteger("code") == 99){
                    token = getToken();
                    result = httpGetRequest(url);
                }else{
                    result = "0";
                }
            } else {
                System.out.println("responseString");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String getToken() throws UnsupportedEncodingException {//初始化后直接登录
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(LOGIN_URL);
        List<NameValuePair> pairs = new ArrayList<>();
        pairs.add(new BasicNameValuePair("name", LOGIN_NAME));
        pairs.add(new BasicNameValuePair("password", LOGIN_PASSWORD));
        UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(pairs, "utf-8");
        urlEncodedFormEntity.setContentType("application/x-www-form-urlencoded");
        httpPost.setEntity(urlEncodedFormEntity);
        String result = "";
        try {
            HttpResponse response = httpClient.execute(httpPost);
            String resultStr = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSONObject.parseObject(resultStr);
            if(jsonObject.getBoolean("status")){
                result = jsonObject.getString("obj");
                System.out.println(result + "这里是登录结果++++++++++++++++");
            }else{
                result = "";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

     public static void main(String[] args) throws UnsupportedEncodingException {

         //String deCodeStr ="HZ01,525578a0b87f11e78377515bf61536c9,10,12921,1,";

         // String deCodeStr ="HZ02,525db600b87f11e78377515bf61536c9,40,";
         //String deCodeStr ="HZ03,525f8ac0b87f11e78377515bf61536c9,10,";
         //String deCodeStr ="HZ04,52629800b87f11e78377515bf61536c9,20,";
         //String deCodeStr ="HZ05,52641ea0b87f11e78377515bf61536c9,10,36,0,";
         String deCodeStr = "HZ05,52641ea0b87f11e78377515bf61536c9,30,,,";
         Map<String,Object> params = new HashMap<>();
         if(deCodeStr.toLowerCase().startsWith("hz")){
             if(deCodeStr.toLowerCase().startsWith("hz01") || deCodeStr.toLowerCase().startsWith("hz02") || deCodeStr.toLowerCase().startsWith("hz03")
                     || deCodeStr.toLowerCase().startsWith("hz04") || deCodeStr.toLowerCase().startsWith("hz05")){
                 System.out.println(deCodeStr);
                 params.put("mark", deCodeStr.split(",")[0]);
                 params.put("data", deCodeStr.substring(deCodeStr.indexOf(",")+1));
             }
         }else{
             params = (Map) JSON.parse(deCodeStr);
         }
         //关键逻辑，调用httpClient 把短信发送到报警端
         HttpClientUtils.get(params);

     }

}
